/**
 * @author Dave
 */
(function() {
	cmx.tree.SiteTreePanel = function(configs) {
		// apply additional configs to base params
		Ext.apply(configs, {
				title: 'Site Explorer',
				enableDD:true,
				animate:true,
				loader: new Ext.tree.TreeLoader({
		            dataUrl:'lib/php/GetSiteTreeNodes.php'
		        })
			});
			
		cmx.tree.SiteTreePanel.superclass.constructor.call(this, configs);
		
		this.on('contextmenu', this.onContextMenu, this);
		this.getLoader().on('beforeload', function(treeLoader, node) {
				treeLoader.baseParams.type = node.attributes.type;
			});
		
		// set the root node
	    this.setRootNode(new Ext.tree.AsyncTreeNode({
		        text: 'My Sites',
		        draggable:false,
		        id:'root',
		        type:'root'
		    }));		    	  
	    this.root.expand();	    	    	  
	}
	
	Ext.extend(cmx.tree.SiteTreePanel, Ext.tree.TreePanel, {
		onContextMenu : function(node, e){
	        if(!this.menu){ // create context menu on first right click
	            this.menu = new Ext.menu.Menu({
	                id:'site-ctx',
	                items: [{
	                    id:'load',
	                    iconCls:'load-icon',
	                    text:'Load Feed',
	                    scope: this,
	                    handler:function(){
	                        this.ctxNode.select();
	                    }
	                },{
	                    text:'Remove',
	                    iconCls:'delete-icon',
	                    scope: this,
	                    handler:function(){
	                        this.ctxNode.ui.removeClass('x-node-ctx');
	                        this.removeFeed(this.ctxNode.attributes.url);
	                        this.ctxNode = null;
	                    }
	                },'-',{
	                    iconCls:'add-feed',
	                    text:'Add Feed',
	                    handler: this.showWindow,
	                    scope: this
	                }]
	            });
	            this.menu.on('hide', this.onContextHide, this);
	        }
	        
	        if(this.ctxNode){
	            this.ctxNode.ui.removeClass('x-node-ctx');
	            this.ctxNode = null;
	        }
	        
	        if(node.isLeaf()){
	            this.ctxNode = node;
	            this.ctxNode.ui.addClass('x-node-ctx');
	            this.menu.items.get('load').setDisabled(node.isSelected());
	            this.menu.showAt(e.getXY());
	        }
	    },
	
	    onContextHide : function(){
	        if(this.ctxNode){
	            this.ctxNode.ui.removeClass('x-node-ctx');
	            this.ctxNode = null;
	        }
	    },
		
		// prevent the default context menu when you miss the node
		afterRender : function(){			
			cmx.tree.SiteTreePanel.superclass.afterRender.call(this);
				this.el.on('contextmenu', function(e){
				e.preventDefault();
			});
		}
	});
}());